home *** CD-ROM | disk | FTP | other *** search
/ Clickx 115 / Clickx 115.iso / software / tools / windows / tails-i386-0.16.iso / live / filesystem.squashfs / usr / share / arm / starter.py < prev    next >
Encoding:
Python Source  |  2012-05-18  |  24.0 KB  |  580 lines

  1. #!/usr/bin/env python
  2.  
  3. """
  4. Command line application for monitoring Tor relays, providing real time status
  5. information. This is the starter for the application, handling and validating
  6. command line parameters.
  7. """
  8.  
  9. import os
  10. import sys
  11. import time
  12. import getopt
  13. import getpass
  14. import locale
  15. import platform
  16.  
  17. import version
  18. import cli.controller
  19. import cli.logPanel
  20. import util.conf
  21. import util.connections
  22. import util.hostnames
  23. import util.log
  24. import util.panel
  25. import util.procTools
  26. import util.sysTools
  27. import util.torConfig
  28. import util.torInterpretor
  29. import util.torTools
  30. import util.uiTools
  31. import TorCtl.TorCtl
  32. import TorCtl.TorUtil
  33.  
  34. LOG_DUMP_PATH = os.path.expanduser("~/.arm/log")
  35. DEFAULT_CONFIG = os.path.expanduser("~/.arm/armrc")
  36. CONFIG = {"startup.controlPassword": None,
  37.           "startup.interface.ipAddress": "127.0.0.1",
  38.           "startup.interface.port": 9051,
  39.           "startup.interface.socket": "/var/run/tor/control",
  40.           "startup.blindModeEnabled": False,
  41.           "startup.events": "N3",
  42.           "startup.dataDirectory": "~/.arm",
  43.           "wizard.default": {},
  44.           "features.allowDetachedStartup": True,
  45.           "features.config.descriptions.enabled": True,
  46.           "features.config.descriptions.persist": True,
  47.           "log.configDescriptions.readManPageSuccess": util.log.INFO,
  48.           "log.configDescriptions.readManPageFailed": util.log.NOTICE,
  49.           "log.configDescriptions.internalLoadSuccess": util.log.NOTICE,
  50.           "log.configDescriptions.internalLoadFailed": util.log.ERR,
  51.           "log.configDescriptions.persistance.loadSuccess": util.log.INFO,
  52.           "log.configDescriptions.persistance.loadFailed": util.log.INFO,
  53.           "log.configDescriptions.persistance.saveSuccess": util.log.INFO,
  54.           "log.configDescriptions.persistance.saveFailed": util.log.NOTICE,
  55.           "log.savingDebugLog": util.log.NOTICE}
  56.  
  57. OPT = "gpi:s:c:dbe:vh"
  58. OPT_EXPANDED = ["gui", "prompt", "interface=", "socket=", "config=", "debug", "blind", "event=", "version", "help"]
  59.  
  60. HELP_MSG = """Usage arm [OPTION]
  61. Terminal status monitor for Tor relays.
  62.  
  63.   -g, --gui                       launch the Gtk+ interface
  64.   -p, --prompt                    only start the control interpretor
  65.   -i, --interface [ADDRESS:]PORT  change control interface from %s:%i
  66.   -s, --socket SOCKET_PATH        attach using unix domain socket if present,
  67.                                     SOCKET_PATH defaults to: %s
  68.   -c, --config CONFIG_PATH        loaded configuration options, CONFIG_PATH
  69.                                     defaults to: %s
  70.   -d, --debug                     writes all arm logs to %s
  71.   -b, --blind                     disable connection lookups
  72.   -e, --event EVENT_FLAGS         event types in message log  (default: %s)
  73. %s
  74.   -v, --version                   provides version information
  75.   -h, --help                      presents this help
  76.  
  77. Example:
  78. arm -b -i 1643          hide connection data, attaching to control port 1643
  79. arm -e we -c /tmp/cfg   use this configuration file with 'WARN'/'ERR' events
  80. """ % (CONFIG["startup.interface.ipAddress"], CONFIG["startup.interface.port"], CONFIG["startup.interface.socket"], DEFAULT_CONFIG, LOG_DUMP_PATH, CONFIG["startup.events"], cli.logPanel.EVENT_LISTING)
  81.  
  82. # filename used for cached tor config descriptions
  83. CONFIG_DESC_FILENAME = "torConfigDesc.txt"
  84.  
  85. # messages related to loading the tor configuration descriptions
  86. DESC_LOAD_SUCCESS_MSG = "Loaded configuration descriptions from '%s' (runtime: %0.3f)"
  87. DESC_LOAD_FAILED_MSG = "Unable to load configuration descriptions (%s)"
  88. DESC_INTERNAL_LOAD_SUCCESS_MSG = "Falling back to descriptions for Tor %s"
  89. DESC_INTERNAL_LOAD_FAILED_MSG = "Unable to load fallback descriptions. Categories and help for Tor's configuration options won't be available. (%s)"
  90. DESC_READ_MAN_SUCCESS_MSG = "Read descriptions for tor's configuration options from its man page (runtime %0.3f)"
  91. DESC_READ_MAN_FAILED_MSG = "Unable to get the descriptions of Tor's configuration options from its man page (%s)"
  92. DESC_SAVE_SUCCESS_MSG = "Saved configuration descriptions to '%s' (runtime: %0.3f)"
  93. DESC_SAVE_FAILED_MSG = "Unable to save configuration descriptions (%s)"
  94.  
  95. NO_INTERNAL_CFG_MSG = "Failed to load the parsing configuration. This will be problematic for a few things like torrc validation and log duplication detection (%s)"
  96. STANDARD_CFG_LOAD_FAILED_MSG = "Failed to load configuration (using defaults): \"%s\""
  97. STANDARD_CFG_NOT_FOUND_MSG = "No armrc loaded, using defaults. You can customize arm by placing a configuration file at '%s' (see the armrc.sample for its options)."
  98.  
  99. # torrc entries that are scrubbed when dumping
  100. PRIVATE_TORRC_ENTRIES = ["HashedControlPassword", "Bridge", "HiddenServiceDir"]
  101.  
  102. # notices given if the user is running arm or tor as root
  103. TOR_ROOT_NOTICE = "Tor is currently running with root permissions. This is not a good idea and shouldn't be necessary. See the 'User UID' option from Tor's man page for an easy method of reducing its permissions after startup."
  104. ARM_ROOT_NOTICE = "Arm is currently running with root permissions. This is not a good idea, and will still work perfectly well if it's run with the same user as Tor (ie, starting with \"sudo -u %s arm\")."
  105.  
  106. # Makes subcommands provide us with English results (this is important so we
  107. # can properly parse it).
  108.  
  109. os.putenv("LANG", "C")
  110.  
  111. def allowConnectionTypes():
  112.   """
  113.   This provides a tuple with booleans indicating if we should or shouldn't
  114.   attempt to connect by various methods...
  115.   (allowPortConnection, allowSocketConnection, allowDetachedStart)
  116.   """
  117.   
  118.   confKeys = util.conf.getConfig("arm").getKeys()
  119.   
  120.   isPortArgPresent = "startup.interface.ipAddress" in confKeys or "startup.interface.port" in confKeys
  121.   isSocketArgPresent = "startup.interface.socket" in confKeys
  122.   
  123.   skipPortConnection = isSocketArgPresent and not isPortArgPresent
  124.   skipSocketConnection = isPortArgPresent and not isSocketArgPresent
  125.   
  126.   # Flag to indicate if we'll start arm reguardless of being unable to connect
  127.   # to Tor. This is the default behavior if the user hasn't provided a port or
  128.   # socket to connect to, so we can show the relay setup wizard.
  129.   
  130.   allowDetachedStart = CONFIG["features.allowDetachedStartup"] and not isPortArgPresent and not isSocketArgPresent
  131.   
  132.   return (not skipPortConnection, not skipSocketConnection, allowDetachedStart)
  133.  
  134. def _loadConfigurationDescriptions(pathPrefix):
  135.   """
  136.   Attempts to load descriptions for tor's configuration options, fetching them
  137.   from the man page and persisting them to a file to speed future startups.
  138.   """
  139.   
  140.   # It is important that this is loaded before entering the curses context,
  141.   # otherwise the man call pegs the cpu for around a minute (I'm not sure
  142.   # why... curses must mess the terminal in a way that's important to man).
  143.   
  144.   if CONFIG["features.config.descriptions.enabled"]:
  145.     isConfigDescriptionsLoaded = False
  146.     
  147.     # determines the path where cached descriptions should be persisted (left
  148.     # undefined if caching is disabled)
  149.     descriptorPath = None
  150.     if CONFIG["features.config.descriptions.persist"]:
  151.       dataDir = CONFIG["startup.dataDirectory"]
  152.       if not dataDir.endswith("/"): dataDir += "/"
  153.       
  154.       descriptorPath = os.path.expanduser(dataDir + "cache/") + CONFIG_DESC_FILENAME
  155.     
  156.     # attempts to load configuration descriptions cached in the data directory
  157.     if descriptorPath:
  158.       try:
  159.         loadStartTime = time.time()
  160.         util.torConfig.loadOptionDescriptions(descriptorPath)
  161.         isConfigDescriptionsLoaded = True
  162.         
  163.         msg = DESC_LOAD_SUCCESS_MSG % (descriptorPath, time.time() - loadStartTime)
  164.         util.log.log(CONFIG["log.configDescriptions.persistance.loadSuccess"], msg)
  165.       except IOError, exc:
  166.         msg = DESC_LOAD_FAILED_MSG % util.sysTools.getFileErrorMsg(exc)
  167.         util.log.log(CONFIG["log.configDescriptions.persistance.loadFailed"], msg)
  168.     
  169.     # fetches configuration options from the man page
  170.     if not isConfigDescriptionsLoaded:
  171.       try:
  172.         loadStartTime = time.time()
  173.         util.torConfig.loadOptionDescriptions()
  174.         isConfigDescriptionsLoaded = True
  175.         
  176.         msg = DESC_READ_MAN_SUCCESS_MSG % (time.time() - loadStartTime)
  177.         util.log.log(CONFIG["log.configDescriptions.readManPageSuccess"], msg)
  178.       except IOError, exc:
  179.         msg = DESC_READ_MAN_FAILED_MSG % util.sysTools.getFileErrorMsg(exc)
  180.         util.log.log(CONFIG["log.configDescriptions.readManPageFailed"], msg)
  181.       
  182.       # persists configuration descriptions 
  183.       if isConfigDescriptionsLoaded and descriptorPath:
  184.         try:
  185.           loadStartTime = time.time()
  186.           util.torConfig.saveOptionDescriptions(descriptorPath)
  187.           
  188.           msg = DESC_SAVE_SUCCESS_MSG % (descriptorPath, time.time() - loadStartTime)
  189.           util.log.log(CONFIG["log.configDescriptions.persistance.loadSuccess"], msg)
  190.         except (IOError, OSError), exc:
  191.           msg = DESC_SAVE_FAILED_MSG % util.sysTools.getFileErrorMsg(exc)
  192.           util.log.log(CONFIG["log.configDescriptions.persistance.saveFailed"], msg)
  193.     
  194.     # finally fall back to the cached descriptors provided with arm (this is
  195.     # often the case for tbb and manual builds)
  196.     if not isConfigDescriptionsLoaded:
  197.       try:
  198.         loadStartTime = time.time()
  199.         loadedVersion = util.torConfig.loadOptionDescriptions("%sresources/%s" % (pathPrefix, CONFIG_DESC_FILENAME), False)
  200.         isConfigDescriptionsLoaded = True
  201.         
  202.         msg = DESC_INTERNAL_LOAD_SUCCESS_MSG % loadedVersion
  203.         util.log.log(CONFIG["log.configDescriptions.internalLoadSuccess"], msg)
  204.       except IOError, exc:
  205.         msg = DESC_INTERNAL_LOAD_FAILED_MSG % util.sysTools.getFileErrorMsg(exc)
  206.         util.log.log(CONFIG["log.configDescriptions.internalLoadFailed"], msg)
  207.  
  208. def _torCtlConnect(controlAddr="127.0.0.1", controlPort=9051, passphrase=None, incorrectPasswordMsg="", printError=True):
  209.   """
  210.   Custom handler for establishing a TorCtl connection.
  211.   """
  212.   
  213.   conn = None
  214.   try:
  215.     #conn, authType, authValue = TorCtl.TorCtl.preauth_connect(controlAddr, controlPort)
  216.     conn, authTypes, authValue = util.torTools.preauth_connect_alt(controlAddr, controlPort)
  217.     
  218.     if TorCtl.TorCtl.AUTH_TYPE.PASSWORD in authTypes:
  219.       # password authentication, promting for the password if it wasn't provided
  220.       #
  221.       # TODO: When handling multi-auth we should try to authenticate via the
  222.       # cookie first, then fall back to prompting the user for their password.
  223.       # With the stack of fixes and hacks we have here jerry-rigging that in
  224.       # without trying cookie auth twice will be a pita so leaving this alone
  225.       # for now. Stem will handle most of this transparently, letting us handle
  226.       # this much more elegantly.
  227.       
  228.       if not passphrase:
  229.         try: passphrase = getpass.getpass("Controller password: ")
  230.         except KeyboardInterrupt: return None
  231.     
  232.     if TorCtl.TorCtl.AUTH_TYPE.COOKIE in authTypes and authValue[0] != "/":
  233.       # Connecting to the control port will probably fail if it's using cookie
  234.       # authentication and the cookie path is relative (unfortunately this is
  235.       # the case for TBB). This is discussed in:
  236.       # https://trac.torproject.org/projects/tor/ticket/1101
  237.       #
  238.       # This is best effort. If we can't expand the path then it's still
  239.       # attempted since we might be running in tor's pwd.
  240.       
  241.       torPid = util.torTools.getPid(controlPort)
  242.       if torPid:
  243.         try: conn._cookiePath = util.sysTools.expandRelativePath(authValue, torPid)
  244.         except IOError: pass
  245.     
  246.     # appends the path prefix if it's set
  247.     if TorCtl.TorCtl.AUTH_TYPE.COOKIE in authTypes:
  248.       pathPrefix = util.torTools.getConn().getPathPrefix()
  249.       
  250.       # The os.path.join function is kinda stupid. If given an absolute path
  251.       # with the second argument then it will swallow the prefix. Ie...
  252.       # os.path.join("/tmp", "/foo") => "/foo"
  253.       
  254.       if pathPrefix:
  255.         pathSuffix = conn._cookiePath
  256.         if pathSuffix.startswith("/"): pathSuffix = pathSuffix[1:]
  257.         
  258.         conn._cookiePath = os.path.join(pathPrefix, pathSuffix)
  259.       
  260.       # Abort if the file isn't 32 bytes long. This is to avoid exposing
  261.       # arbitrary file content to the port.
  262.       #
  263.       # Without this a malicious socket could, for instance, claim that
  264.       # '~/.bash_history' or '~/.ssh/id_rsa' was its authentication cookie to
  265.       # trick us into reading it for them with our current permissions.
  266.       #
  267.       # https://trac.torproject.org/projects/tor/ticket/4305
  268.       
  269.       try:
  270.         authCookieSize = os.path.getsize(conn._cookiePath)
  271.         if authCookieSize != 32:
  272.           raise IOError("authentication cookie '%s' is the wrong size (%i bytes instead of 32)" % (conn._cookiePath, authCookieSize))
  273.       except Exception, exc:
  274.         # if the above fails then either...
  275.         # - raise an exception if cookie auth is the only method we have to
  276.         #   authenticate
  277.         # - suppress the exception and try the other connection methods if we
  278.         #   have alternatives
  279.         if len(authTypes) == 1: raise exc
  280.         else: conn._authTypes.remove(TorCtl.TorCtl.AUTH_TYPE.COOKIE)
  281.     
  282.     conn.authenticate(passphrase)
  283.     return conn
  284.   except Exception, exc:
  285.     if conn: conn.close()
  286.     
  287.     # attempts to connect with the default wizard address too
  288.     wizardPort = CONFIG["wizard.default"].get("Control")
  289.     
  290.     if wizardPort and wizardPort.isdigit():
  291.       wizardPort = int(wizardPort)
  292.       
  293.       # Attempt to connect to the wizard port. If the connection fails then
  294.       # don't print anything and continue with the error case for the initial
  295.       # connection failure. Otherwise, return the connection result.
  296.       
  297.       if controlPort != wizardPort:
  298.         connResult = _torCtlConnect(controlAddr, wizardPort)
  299.         if connResult != None: return connResult
  300.       else: return None # wizard connection attempt, don't print anything
  301.     
  302.     if passphrase and str(exc) == "Unable to authenticate: password incorrect":
  303.       # provide a warning that the provided password didn't work, then try
  304.       # again prompting for the user to enter it
  305.       print incorrectPasswordMsg
  306.       return _torCtlConnect(controlAddr, controlPort)
  307.     elif printError:
  308.       print exc
  309.       return None
  310.  
  311. def _dumpConfig():
  312.   """
  313.   Dumps the current arm and tor configurations at the DEBUG runlevel. This
  314.   attempts to scrub private information, but naturally the user should double
  315.   check that I didn't miss anything.
  316.   """
  317.   
  318.   config = util.conf.getConfig("arm")
  319.   conn = util.torTools.getConn()
  320.   
  321.   # dumps arm's configuration
  322.   armConfigEntry = ""
  323.   armConfigKeys = list(config.getKeys())
  324.   armConfigKeys.sort()
  325.   
  326.   for configKey in armConfigKeys:
  327.     # Skips some config entries that are loaded by default. This fetches
  328.     # the config values directly to avoid misflagging them as being used by
  329.     # arm.
  330.     
  331.     if not configKey.startswith("config.summary.") and not configKey.startswith("torrc.") and not configKey.startswith("msg."):
  332.       armConfigEntry += "%s -> %s\n" % (configKey, config.contents[configKey])
  333.   
  334.   if armConfigEntry: armConfigEntry = "Arm Configuration:\n%s" % armConfigEntry
  335.   else: armConfigEntry = "Arm Configuration: None"
  336.   
  337.   # dumps tor's version and configuration
  338.   torConfigEntry = "Tor (%s) Configuration:\n" % conn.getInfo("version")
  339.   
  340.   for line in conn.getInfo("config-text", "").split("\n"):
  341.     if not line: continue
  342.     elif " " in line: key, value = line.split(" ", 1)
  343.     else: key, value = line, ""
  344.     
  345.     if key in PRIVATE_TORRC_ENTRIES:
  346.       torConfigEntry += "%s <scrubbed>\n" % key
  347.     else:
  348.       torConfigEntry += "%s %s\n" % (key, value)
  349.   
  350.   util.log.log(util.log.DEBUG, armConfigEntry.strip())
  351.   util.log.log(util.log.DEBUG, torConfigEntry.strip())
  352.  
  353. if __name__ == '__main__':
  354.   startTime = time.time()
  355.   param = dict([(key, None) for key in CONFIG.keys()])
  356.   launchGui = False
  357.   launchPrompt = False
  358.   isDebugMode = False
  359.   configPath = DEFAULT_CONFIG # path used for customized configuration
  360.   
  361.   # parses user input, noting any issues
  362.   try:
  363.     opts, args = getopt.getopt(sys.argv[1:], OPT, OPT_EXPANDED)
  364.   except getopt.GetoptError, exc:
  365.     print str(exc) + " (for usage provide --help)"
  366.     sys.exit()
  367.   
  368.   for opt, arg in opts:
  369.     if opt in ("-i", "--interface"):
  370.       # defines control interface address/port
  371.       controlAddr, controlPort = None, None
  372.       divIndex = arg.find(":")
  373.       
  374.       try:
  375.         if divIndex == -1:
  376.           controlPort = int(arg)
  377.         else:
  378.           controlAddr = arg[0:divIndex]
  379.           controlPort = int(arg[divIndex + 1:])
  380.       except ValueError:
  381.         print "'%s' isn't a valid port number" % arg
  382.         sys.exit()
  383.       
  384.       param["startup.interface.ipAddress"] = controlAddr
  385.       param["startup.interface.port"] = controlPort
  386.     elif opt in ("-s", "--socket"):
  387.       param["startup.interface.socket"] = arg
  388.     elif opt in ("-g", "--gui"): launchGui = True
  389.     elif opt in ("-p", "--prompt"): launchPrompt = True
  390.     elif opt in ("-c", "--config"): configPath = arg  # sets path of user's config
  391.     elif opt in ("-d", "--debug"): isDebugMode = True # dumps all logs
  392.     elif opt in ("-b", "--blind"):
  393.       param["startup.blindModeEnabled"] = True        # prevents connection lookups
  394.     elif opt in ("-e", "--event"):
  395.       param["startup.events"] = arg                   # set event flags
  396.     elif opt in ("-v", "--version"):
  397.       print "arm version %s (released %s)\n" % (version.VERSION, version.LAST_MODIFIED)
  398.       sys.exit()
  399.     elif opt in ("-h", "--help"):
  400.       print HELP_MSG
  401.       sys.exit()
  402.   
  403.   if isDebugMode:
  404.     try:
  405.       util.log.setDumpFile(LOG_DUMP_PATH)
  406.       
  407.       currentTime = time.localtime()
  408.       timeLabel = time.strftime("%H:%M:%S %m/%d/%Y (%Z)", currentTime)
  409.       initMsg = "Arm %s Debug Dump, %s" % (version.VERSION, timeLabel)
  410.       pythonVersionLabel = "Python Version: %s" % (".".join([str(arg) for arg in sys.version_info[:3]]))
  411.       osLabel = "Platform: %s (%s)" % (platform.system(), " ".join(platform.dist()))
  412.       
  413.       util.log.DUMP_FILE.write("%s\n%s\n%s\n%s\n" % (initMsg, pythonVersionLabel, osLabel, "-" * 80))
  414.       util.log.DUMP_FILE.flush()
  415.     except (OSError, IOError), exc:
  416.       print "Unable to write to debug log file: %s" % util.sysTools.getFileErrorMsg(exc)
  417.   
  418.   config = util.conf.getConfig("arm")
  419.   
  420.   # attempts to fetch attributes for parsing tor's logs, configuration, etc
  421.   pathPrefix = os.path.dirname(sys.argv[0])
  422.   if pathPrefix and not pathPrefix.endswith("/"):
  423.     pathPrefix = pathPrefix + "/"
  424.   
  425.   try:
  426.     config.load("%ssettings.cfg" % pathPrefix)
  427.   except IOError, exc:
  428.     msg = NO_INTERNAL_CFG_MSG % util.sysTools.getFileErrorMsg(exc)
  429.     util.log.log(util.log.WARN, msg)
  430.   
  431.   # loads user's personal armrc if available
  432.   if os.path.exists(configPath):
  433.     try:
  434.       config.load(configPath)
  435.     except IOError, exc:
  436.       msg = STANDARD_CFG_LOAD_FAILED_MSG % util.sysTools.getFileErrorMsg(exc)
  437.       util.log.log(util.log.WARN, msg)
  438.   else:
  439.     # no armrc found, falling back to the defaults in the source
  440.     msg = STANDARD_CFG_NOT_FOUND_MSG % configPath
  441.     util.log.log(util.log.NOTICE, msg)
  442.   
  443.   # prevent arm from starting without a tor instance if...
  444.   # - we're launching a prompt
  445.   # - tor is running (otherwise it would be kinda confusing, "tor is running
  446.   #   but why does arm say that it's shut down?")
  447.   
  448.   if launchPrompt or util.torTools.isTorRunning():
  449.     config.set("features.allowDetachedStartup", "false")
  450.   
  451.   # revises defaults to match user's configuration
  452.   config.update(CONFIG)
  453.   
  454.   # loads user preferences for utilities
  455.   for utilModule in (util.conf, util.connections, util.hostnames, util.log, util.panel, util.procTools, util.sysTools, util.torConfig, util.torTools, util.uiTools):
  456.     utilModule.loadConfig(config)
  457.   
  458.   # syncs config and parameters, saving changed config options and overwriting
  459.   # undefined parameters with defaults
  460.   for key in param.keys():
  461.     if param[key] == None: param[key] = CONFIG[key]
  462.     else: config.set(key, str(param[key]))
  463.   
  464.   # validates that input has a valid ip address and port
  465.   controlAddr = param["startup.interface.ipAddress"]
  466.   controlPort = param["startup.interface.port"]
  467.   
  468.   if not util.connections.isValidIpAddress(controlAddr):
  469.     print "'%s' isn't a valid IP address" % controlAddr
  470.     sys.exit()
  471.   elif controlPort < 0 or controlPort > 65535:
  472.     print "'%s' isn't a valid port number (ports range 0-65535)" % controlPort
  473.     sys.exit()
  474.   
  475.   # validates and expands log event flags
  476.   try:
  477.     cli.logPanel.expandEvents(param["startup.events"])
  478.   except ValueError, exc:
  479.     for flag in str(exc):
  480.       print "Unrecognized event flag: %s" % flag
  481.     sys.exit()
  482.   
  483.   # temporarily disables TorCtl logging to prevent issues from going to stdout while starting
  484.   TorCtl.TorUtil.loglevel = "NONE"
  485.   
  486.   # By default attempts to connect using the control socket if it exists. This
  487.   # skips attempting to connect by socket or port if the user has given
  488.   # arguments for connecting to the other.
  489.   
  490.   conn = None
  491.   allowPortConnection, allowSocketConnection, allowDetachedStart = allowConnectionTypes()
  492.   
  493.   socketPath = param["startup.interface.socket"]
  494.   if os.path.exists(socketPath) and allowSocketConnection:
  495.     try: conn = util.torTools.connect_socket(socketPath)
  496.     except IOError, exc:
  497.       if not allowPortConnection:
  498.         print "Unable to use socket '%s': %s" % (socketPath, exc)
  499.   elif not allowPortConnection:
  500.     print "Socket '%s' doesn't exist" % socketPath
  501.   
  502.   if not conn and allowPortConnection:
  503.     # sets up TorCtl connection, prompting for the passphrase if necessary and
  504.     # sending problems to stdout if they arise
  505.     authPassword = config.get("startup.controlPassword", CONFIG["startup.controlPassword"])
  506.     incorrectPasswordMsg = "Password found in '%s' was incorrect" % configPath
  507.     conn = _torCtlConnect(controlAddr, controlPort, authPassword, incorrectPasswordMsg, not allowDetachedStart)
  508.     
  509.     # removing references to the controller password so the memory can be freed
  510.     # (unfortunately python does allow for direct access to the memory so this
  511.     # is the best we can do)
  512.     del authPassword
  513.     if "startup.controlPassword" in config.contents:
  514.       del config.contents["startup.controlPassword"]
  515.       
  516.       pwLineNum = None
  517.       for i in range(len(config.rawContents)):
  518.         if config.rawContents[i].strip().startswith("startup.controlPassword"):
  519.           pwLineNum = i
  520.           break
  521.       
  522.       if pwLineNum != None:
  523.         del config.rawContents[i]
  524.   
  525.   if conn == None and not allowDetachedStart: sys.exit(1)
  526.   
  527.   # initializing the connection may require user input (for the password)
  528.   # skewing the startup time results so this isn't counted
  529.   initTime = time.time() - startTime
  530.   controller = util.torTools.getConn()
  531.   
  532.   torUser = None
  533.   if conn:
  534.     controller.init(conn)
  535.     
  536.     # give a notice if tor is running with root
  537.     torUser = controller.getMyUser()
  538.     if torUser == "root":
  539.       util.log.log(util.log.NOTICE, TOR_ROOT_NOTICE)
  540.   
  541.   # Give a notice if arm is running with root. Querying connections usually
  542.   # requires us to have the same permissions as tor so if tor is running as
  543.   # root then drop this notice (they're already then being warned about tor
  544.   # being root, anyway).
  545.   
  546.   if torUser != "root" and os.getuid() == 0:
  547.     torUserLabel = torUser if torUser else "<tor user>"
  548.     util.log.log(util.log.NOTICE, ARM_ROOT_NOTICE % torUserLabel)
  549.   
  550.   # fetches descriptions for tor's configuration options
  551.   _loadConfigurationDescriptions(pathPrefix)
  552.   
  553.   # dump tor and arm configuration when in debug mode
  554.   if isDebugMode:
  555.     util.log.log(CONFIG["log.savingDebugLog"], "Saving a debug log to '%s' (please check it for sensitive information before sharing)" % LOG_DUMP_PATH)
  556.     _dumpConfig()
  557.   
  558.   # Attempts to rename our process from "python setup.py <input args>" to
  559.   # "arm <input args>"
  560.   
  561.   try:
  562.     from util import procName
  563.     procName.renameProcess("arm\0%s" % "\0".join(sys.argv[1:]))
  564.   except: pass
  565.   
  566.   # If using our LANG variable for rendering multi-byte characters lets us
  567.   # get unicode support then then use it. This needs to be done before
  568.   # initializing curses.
  569.   if util.uiTools.isUnicodeAvailable():
  570.     locale.setlocale(locale.LC_ALL, "")
  571.   
  572.   if launchGui:
  573.     import gui.controller
  574.     gui.controller.start_gui()
  575.   elif launchPrompt:
  576.     util.torInterpretor.showPrompt()
  577.   else:
  578.     cli.controller.startTorMonitor(time.time() - initTime)
  579.  
  580.